import { MongoClient, Db, Collection } from "mongodb";

/** 官方 node-mongodb-native = npm/mongodb */
export class MongodbClient {
  logger: boolean = false;
  serverAddress: string;
  serverClient!: MongoClient;

  /** 通过一个客户端去控制多个数据库 */
  dbInstance!: Db;

  constructor(address: string, logger?: boolean) {
    this.serverAddress = address;
    this.logger = !!logger;
  }

  async start() {
    const client: MongoClient = await MongoClient.connect(this.serverAddress);
    this.serverClient = client;

    const databaseName = this.serverAddress.split("/").reverse()[0];
    this.dbInstance = client.db(databaseName);
    const collections = await this.dbInstance.listCollections().toArray();

    this.logger && console.log("🏀 MongoDB > 初始化成功（1）数据库控制器（2）数据库实例", databaseName, collections.length);
  }

  async stop() {
    this.serverClient && (await this.serverClient.close());
    this.logger && console.log("🏀 MongoDB > 数据库控制器：已经关闭数据库实例");
  }

  private collectionCache = new Map<string, Collection>();
  getCollection(collectionName: string): Collection {
    const cache = this.collectionCache.get(collectionName);
    if (cache) return cache;

    const collection = this.dbInstance.collection(collectionName);
    this.collectionCache.set(collectionName, collection);
    return collection;
  }
}
